package com.xlh.outside;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.wzm.param.ApiResultPo.AddUserReslult;
import com.wzm.param.ApiResultPo.GetVerReslult;
import com.wzm.param.ApiResultPo.LoginReslult;
import com.xlh.Model.ButCmdsModel;
import com.xlh.Model.LoginLogModel;
import com.xlh.Utils.FUti;
import com.xlh.Utils.GsonManager;
import com.xlh.bean.DataBase.ButCmd;
import com.xlh.bean.DataBase.UserBean;
import com.xlh.conf.CommonConf;
import com.xlh.interf.IUiUpdateHandler;
import com.xlh.lib.Core.FFCursorHelper;
import com.xlh.lib.Core.FIntent;
import com.xlh.thread.TestTask;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by mike on 2017-12-19.
 */

public class LoginActivity extends  BaseActivity implements IUiUpdateHandler {

    //读取数据
    LoginLogModel loginLogModel = new LoginLogModel(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        //Thread th = new Thread(new TestTask(this));
        //th.start();

        //更新



        normalDialog = new AlertDialog.Builder(LoginActivity.this);
        progressDlg = new ProgressDialog( LoginActivity.this);
//        //progressDlg.setTitle("进度对话框测试");  k
//        progressDlg.setMessage("请稍候,正在检查更新....");
//        progressDlg.setIcon(R.drawable.ic_launcher);
//        progressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDlg.setCancelable(false);
//        progressDlg.show();
//
//                Thread th = new Thread(new TestTask()
//                .setContext(LoginActivity.this)
//                .setUrl(CommonConf.API_GET_VER)
//                .setType("getVer")
//        );
//
//        th.start();

        initApi();


        bindControl();
        ininControlEvent();
        initLocalData();
    }


    @Override
    public Handler getHandler() {
        return handler;
    }
    public  FFCursorHelper csrHelper;
    public void bindControl(){
        cEditUserName   =  (EditText) findViewById(R.id.login_edt_username);
        cEditPassword   =  (EditText) findViewById(R.id.login_edt_pwd);
        cButSubmit      =  (Button) findViewById(R.id.login_but_submit);
        cButReg         = (Button) findViewById(R.id.login_but_reg);
    }


    /**
     * 初始化用户管理接口
     * @auth Mike@Fang.j@大当家 Q184377367
     */
    private void initApi(){
        //读取本地配置文件
        String res = FUti.readAssect(getApplicationContext(),"user");
        //转化为实体类
        Map<String,String> data = GsonManager.getIns().jsonToAnyObject(res, Map.class);
        CommonConf.API_USER_REG = data.get("reg");
        CommonConf.API_USER_LOGIN = data.get("login");
        CommonConf.API_USER_UPDATE = data.get("update");

        CommonConf.API_SVR_LIST = data.get("getSvr");

        //读取编码设定
        String charSetConfRes = FUti.readAssect(getApplicationContext(),"charset");
        Map<String,String> charSetData = GsonManager.getIns().jsonToAnyObject(charSetConfRes, Map.class);
        //this.getApp().setCharSet( charSetData.get("charset") );
        CommonConf.CHAR_SET =  charSetData.get("charset");

    }


    public void initLocalData(){
        csrHelper = new FFCursorHelper();
        //不需要更新的时候创建数据库
        csrHelper.setCsr(loginLogModel.getList());

        //本地没有登陆记录
        if(csrHelper.getCsr().getCount() > 0){
            csrHelper.getCsr().moveToLast();
            cEditUserName.setText( csrHelper.getString("username") );
            cEditPassword.setText(csrHelper.getString("password"));
        }
        Log.e("Database============","登陆记录有"+csrHelper.getCsr().getCount()+"条");
        csrHelper.getCsr().close();

    }

    public void ininControlEvent(){





        handler = new Handler(){

            @Override
            public void handleMessage(Message msg) {

                String res  = msg.getData().getCharSequence("result").toString();
                progressDlg.dismiss();
                if(msg.getData().get("type")!=null && msg.getData().get("type")=="getVer"){
//                    GetVerReslult data = GsonManager.getIns().jsonToAnyObject(res,GetVerReslult.class);
//                    //如果服务器关闭，data会为NULL
//                    if(data.getCode()==1){
//                        if(!data.getData().equals(CommonConf.appVer)){
//                            //禁用按钮
//                            cButSubmit.setVisibility(View.GONE);
//                            cButReg.setVisibility(View.GONE);
//
//                            normalDialog.setTitle("提示")
//                                        .setMessage("已检测到有最新版本，请下载更新！")
//                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                            @Override
//                                            public void onClick(DialogInterface dialog, int which) {
//                                                //强制退出
//                                                //System.exit(0);
//                                                Intent intent = new Intent();
//                                                intent.setData(Uri.parse(CommonConf.appDownUrl));
//                                                intent.setAction(Intent.ACTION_VIEW);
//                                                LoginActivity.this.startActivity(intent); //启动浏览器
//                                               System.exit(0);
//
//
//                                            }
//                                        }).show();
//
//                        }else{
//
//                            initLocalData();
//                        }
//                    }


                }else{

                    if( msg.getData().get("err").equals("true") ){
                        normalDialog.setTitle("提示")
                                .setMessage("网络异常请重新操作!")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).show();
                    }else{

                        LoginReslult data = GsonManager.getIns().jsonToAnyObject(res,LoginReslult.class);
                        if(data.getCode()==1){
                            Toast.makeText(LoginActivity.this, "登陆成功!", Toast.LENGTH_SHORT).show();
                            WzApplication application = (WzApplication)getApplication();
                            application.setActiveUser(cEditUserName.getText().toString());
                            application.setActiveUserPwd(cEditPassword.getText().toString());
                            application.setActiveUserNickName(data.getData().getNickname());
                            application.setActiveUserSex(data.getData().getSex());
                            application.setActiveUserPhone(data.getData().getPhone());

                            // Cursor c = loginLogModel.getbyUserName(application.getActiveUser());
                            //本地没有记录这个用户
                            //if(c.getCount() <=0){
                            UserBean u = new UserBean();
                            u.setUsername( application.getActiveUser() );
                            u.setPassword( application.getActiveUserPwd() );
                            loginLogModel.add(u);

                            //  }
                            //c.close();

                            FIntent fIntent = new FIntent(LoginActivity.this, ServerListActivity.class);
                            startActivity(fIntent);
                            finish();

                        }else{
                            Toast.makeText(LoginActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
                        }


                    }








                }


                super.handleMessage(msg);
            }
        };



        cButReg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FIntent fIntent = new FIntent(LoginActivity.this, RegisterActivity.class);
                startActivity(fIntent);
                finish();
            }
        });

    //登陆按钮
        cButSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName,password,param;
                userName = cEditUserName.getText().toString();

                password = cEditPassword.getText().toString();

                param = String.format("username=%s&password=%s", userName,password);
                progressDlg.setMessage("请稍后,正在登陆....");
                progressDlg.setIcon(R.drawable.ic_launcher);
                progressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDlg.setCancelable(false);
                progressDlg.show();
                Thread th = new Thread(new TestTask()
                        .setContext(LoginActivity.this)
                        .setUrl(CommonConf.API_USER_LOGIN + param)
                );

                th.start();
            }
        });


    }

    private EditText cEditUserName;
    private EditText cEditPassword;
    private Button   cButSubmit;
    private Button   cButReg;
    private Handler handler;
    private   ProgressDialog progressDlg;
    private   AlertDialog.Builder normalDialog;

}
